package com.hc.controller;

import com.hc.domain.Tag;
import com.hc.service.TagService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.validation.Valid;

@Controller
@RequestMapping("/tag")
public class TagController {
    @Resource
    private TagService tagService;

    //@GetMapping("/list")
    //public String list(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
    //                   @RequestParam(value = "pageSize", defaultValue = "10", required = false) Integer pageSize,
    //                   @ModelAttribute("msg") String msg,
    //                   Model model) {
    //    PageBean<Tag> TagIpage = tagService.getTagsWithPage(pageNum, pageSize);
    //    if (msg == null) {
    //        model.addAttribute("msg", "恭喜，查询成功！");
    //    }
    //    model.addAttribute("data", TagIpage);
    //    return "/admin/tag";
    //}

    @GetMapping("/showAdd")
    public String showAdd(Model model) {
        model.addAttribute("tag", new Tag());//数据回显时用
        return "/admin/tag-add-update";
    }


    @GetMapping("/showUpdate/{id}")
    public String showUpdate(@PathVariable("id") Integer id, Model model) {
        Tag tag = tagService.getById(id);
        model.addAttribute("tag", tag);//数据回显时用
        return "/admin/tag-add-update";
    }

    @PostMapping("/update/{id}")
    public String update(@PathVariable("id") Integer id, @Valid Tag tag, BindingResult result, RedirectAttributes attributes) {
        //Tag temp = tagService.getTagByName(tag.getName());
        //if (temp != null) {
        //    result.rejectValue("name", "nameError", "该标签已经存在，不能重复添加！");
        //}
        //if (result.hasErrors()) {
        //    return "/admin/tag-add-update";
        //}
        //int addRes = tagService.modifyTag(id, tag);
        //if (addRes == 1) {//成功
        //    attributes.addFlashAttribute("msg", "恭喜，修改成功！");
        //} else {//失败
        //    attributes.addFlashAttribute("msg", "恭喜，修改失败！");
        //}
        return "redirect:/admin/tag/list";
    }

    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id, RedirectAttributes attributes) {
        int deleteRes = tagService.deleteTagById(id);
        if (deleteRes == 1) {//成功
            attributes.addFlashAttribute("msg", "恭喜，修改成功！");
        } else {//失败
            attributes.addFlashAttribute("msg", "恭喜，修改失败！");
        }
        return "redirect:/admin/tag/list";
    }
}
